package com.party.mobile.biz.analysis;


import com.party.common.utils.HttpServletRequestUtils;
import com.party.common.utils.MD5Util;
import com.party.core.model.analysis.StatisticsUser;
import com.party.core.service.analysis.IStatisticsUserService;
import nl.bitwalker.useragentutils.Browser;
import nl.bitwalker.useragentutils.OperatingSystem;
import nl.bitwalker.useragentutils.UserAgent;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.Date;

/**
 * @program: Project
 * @description: 统计模块_用户分析业务逻辑
 * @author: Huaqunhao
 * @create: 2018-08-07 10:21
 **/
@Service
public class StatisticsUserBizService {

    @Autowired
    private IStatisticsUserService statisticsUserService;

    Logger logger = LoggerFactory.getLogger(getClass());

    /**
     * @Description:
     * @Param: memberId_会员id
     * @Param: name_用户名
     * @Param: logo_用户头像
     * @Param: request
     * @return: HttpServletResponse
     * @Author: Huaqunhao
     * @Date: 2018/8/7/007
     */
    public  String userLoginRecordOperation(String memberId, String name, String logo, HttpServletRequest request) throws Exception {
        //2018/9/10/ 记录用户策略修改：只做保存，不查询，新老用户定时任务统计

        //生成userId___操作系统+浏览器+ip+时间搓

        String userId = this.getStatisticsUserID(request);

        try {
            StatisticsUser statisticsUser = new StatisticsUser();
            statisticsUser.setUserId(userId);
            statisticsUser.setMemberId(memberId);
            statisticsUser.setLogo(logo);
            statisticsUser.setName(name);
            statisticsUser.setEndDate(new Date());
            statisticsUserService.insert(statisticsUser);
        }catch (Exception e){
            logger.error("记录用户异常",e);
        }


/*        StatisticsUser statisticsUser = statisticsUserService.getByUserId(userId);
        //第一次访问
        if (statisticsUser == null) {
            statisticsUser = new StatisticsUser();
            statisticsUser.setUserId(userId);
            statisticsUser.setMemberId(memberId);
            statisticsUser.setLogo(logo);
            statisticsUser.setName(name);
            statisticsUser.setEndDate(new Date());
            statisticsUserService.insert(statisticsUser);
            //记录访问日志
            //statisticsUserVisitBizService.insert("new");
        }
        //已有访问记录
        else {

            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
            String nDate = simpleDateFormat.format(new Date());
            String jDate = simpleDateFormat.format(statisticsUser.getEndDate());
            long nTime= simpleDateFormat.parse(nDate).getTime();
            long jTime= simpleDateFormat.parse(jDate).getTime();

            if(nTime!=jTime){
                statisticsUserVisitBizService.insert("old");
                statisticsUser.setEndDate(new Date());
                statisticsUserService.update(statisticsUser);
            }
        }*/
        return userId;
    }
    /** 
    * @Description: 通过request 获取cookie 中的userID
    * @Param:  
    * @return:  
    * @Author: Huaqunhao
    * @Date: 2018/8/9/009 
    */ 
    public String getStatisticsUserID(HttpServletRequest request) throws Exception {

        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletResponse response = requestAttributes.getResponse();
        Cookie[] cookies = request.getCookies();
        Cookie cookie = null;
        if (cookies != null && cookies.length > 0) {
            for(Cookie c: cookies) {
                if (c.getName().equals("StatisticsUserID")) {
                    cookie = c;
                }
            }
        }
        //如果没有则是新的用户
        if(null==cookie){
            String agent = request.getHeader("User-Agent");
            UserAgent userAgent = UserAgent.parseUserAgentString(agent);
            OperatingSystem operatingSystem = userAgent.getOperatingSystem();
            Browser browser = userAgent.getBrowser();
            //系统名
            String system = operatingSystem.getName();
            //ip地址
            String ipAddress = HttpServletRequestUtils.getRemoteIpAddress(request);
            //浏览器名
            String browserName= browser.getName();
            //设备类型
            String deviceType = operatingSystem.getDeviceType()!=null ?operatingSystem.getDeviceType().getName():"";
            //生成userID
            String uid = URLEncoder.encode(MD5Util.getMD5(system+ipAddress+browserName+deviceType+System.currentTimeMillis()), "utf-8");

            cookie = new Cookie("StatisticsUserID", uid);
        }
        //设置一个月
        int ye = 60*60*24*30;
        cookie.setMaxAge(ye);
        response.addCookie(cookie);

        return URLDecoder.decode(cookie.getValue(), "utf-8");
    }
}
